<template>
    <div class="counter-component">
      <div class="counter-btn" @click="fnSub"> - </div>
      <div class="counter-show">
        <input type="text" v-model="num" @keyup="fnCheckVal">
      </div>
      <div class="counter-btn" @click="fnAdd"> + </div>
    </div>
</template>

<script lang="ts">
  import Vue from 'vue'
  import {Component, Prop, Emit, Watch} from 'vue-property-decorator'

  //引入组件
  @Component
  export default class Counter extends Vue {
    //最大值
    @Prop({ default: 5 })
    max : number

    //最小值
    @Prop({ default: 1 })
    min : number

    //当前值
    num : number = this.min

    @Watch('num')
    onNumChanged() {
        this.emitOnChange(this.num)
    }

    //methods
    //减值
    fnSub():void{
        if (this.num <= this.min) {
            return
        }
        this.num--
    }

    //加值
    fnAdd():void{
      if (this.num >= this.max) {
        return
      }
      this.num++
    }

    //验证值是否为数字
    fnCheckVal():void{
      let fix
      if (typeof this.num === 'string') {
        fix = this.min
      }
      else {
        fix = this.num
      }
      if (fix > this.max || fix < this.min) {
        fix = this.min
      }
      this.num = fix
    }

    //选中值
    @Emit()
    emitOnChange(num: number) { }
  }
</script>

<style lang="scss" scoped>
.counter-component {
  position: relative;
  display: inline-block;
  overflow: hidden;
  vertical-align: middle;

  .counter-show {
    float: left;

    input {
      border: none;
      border-top: 1px solid #e3e3e3;
      border-bottom: 1px solid #e3e3e3;
      height: 23px;
      line-height: 23px;
      width: 30px;
      outline: none;
      text-indent: 4px;
    }
  }

  .counter-btn {
    border: 1px solid #e3e3e3;
    float: left;
    height: 25px;
    line-height: 25px;
    width: 25px;
    text-align: center;
    cursor: pointer;
  }

  .counter-btn:hover {
    border-color: #4fc08d;
    background: #4fc08d;
    color: #fff;
  }
}
</style>
